package io.renren.modules.yckj.common;

import io.renren.common.exception.ErrorCode;
import io.renren.common.exception.RenException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadUtil {

    //获取文件名后缀
    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String getFileName() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static void createPaths(String path) {
        String property = System.getProperty("file.separator");
        String[] paths = path.split(property);
        StringBuffer fullPath = new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append(property);
            File file = new File(fullPath.toString());
            if (paths.length - 1 != i) {//判断path到文件名时，无须继续创建文件夹！
                if (!file.exists()) {
                    file.mkdir();
                    System.out.println("创建目录为：" + fullPath.toString());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public static boolean upload(MultipartFile file, String path, String fileName) {
        //使用原文件名
        String realPath = path + "/" + fileName;
        System.out.println(realPath);
        //判断文件父目录是否存在
//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdir();
//        }
        createPaths(realPath);
        File dest = new File(realPath);
        try {
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String upload(MultipartFile file, String filePath, boolean reName) {
        if (file == null) {
            throw new RenException(ErrorCode.FILE_CODE_ERROR);
        }
        // 要上传的目标文件存放路径
        String fileOriginalFilename = file.getOriginalFilename();
        String fileName = fileOriginalFilename;
        if (reName) {
            try {
                String fileSuffix = getSuffix(fileOriginalFilename);
                fileName = getFileName() + fileSuffix;
            } catch (Exception e) {
                fileName = getFileName() + fileOriginalFilename;
            }
        }
        if (upload(file, filePath, fileName)) {
            return fileName;
        } else {
            throw new RenException(ErrorCode.FILE_CODE_ERROR);
        }
    }

}
